//
//  TKUserCount.swift
//  TKWBOne
//
//  Created by tiankun on 16/9/5.
//  Copyright © 2016年 1. All rights reserved.
//

import UIKit

private let accountFile = "useraccount.json"
//用户账户信息
class TKUserAccount: NSObject {
    var access_token: String?
    var uid: String?
    var expires_in: TimeInterval = 0 {
        didSet {
           expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    //过期日期
    var expiresDate: Date?
    override var description: String {
        return yy_modelDescription()
    }
    override init() {
        super.init()
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = (docDir as NSString).appendingPathComponent(accountFile)
        guard let data = NSData(contentsOfFile: filePath),
        dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String : AnyObject] else {
                return
        }
        //字典转模型
        yy_modelSet(with: dict ?? [:])
        
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            //清空token,uid
            access_token = nil
            uid = nil
            //删除账户文件
            _ = try? FileManager.default.removeItem(atPath: filePath)
        }
    }
    func saveAccount() {
        //模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String : AnyObject]) ?? [:]
        //删除expires_in
        dict.removeValue(forKey: "expires_in")
        //文件路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = (docDir as NSString).appendingPathComponent(accountFile)
        //字典序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
            return
        }
        //写入本地磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        print("用户账户保存成功\(filePath)")
    }
}
